package com.demo.demo4j;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 读取xml文件 dom4j操作
 */
public class HrReader {
    public static void main(String[] args) {
        readXml();
    }

    public static void readXml()   {
        String file="E:\\DemoStudy\\Java\\2020\\12\\2020webDemoAll\\xmlDemo\\src\\main\\java\\xml\\hr.xml";
        //SAXReader类是读取XML文件的核心类，用于将XML解析后以“树”的形式保存在内存中。
        SAXReader saxReader=new SAXReader();
        try {
            Document document=saxReader.read(file);//此处需要添加try/catch
            //获取XML文档的根节点，即hr标签
            Element elementRoot=document.getRootElement();
            //elements方法用于获取指定的标签集合
            List<Element> employees=elementRoot.elements("employee");
            for (Element employee : employees) {
                //element方法用于获取唯一的子节点对象
                Element name=employee.element("name");
                String empName=name.getText();
                System.out.println(empName);

                Element department = employee.element("department");
                System.out.println(department.element("dname").getText());

                Attribute att = employee.attribute("no");
                System.out.println(att.getText());
            }


        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

}
